import { IRouterContext } from "koa-router";
import * as config from "config";
import { sql } from "../util/db";
import { getImgurl } from "../util/imge";
import { PayCycle, Role } from "../enum";
import { getPublicNoFromArticleUrl, PublicNo } from "../util/wechat";
import * as fs from "fs";

export async function countByName(ctx: IRouterContext) {
    const name = ctx.query.name;
    const text = 'select count(id) from t_community where name=$1';
    const res = await sql.query(text, [name]);
    ctx.body = res.rows[0].count;
}

export async function findOneById(ctx: IRouterContext) {
    const community_id = ctx.params.id;
    const text = `select * from t_community where id=$1 and deleted_at is null`;
    const { rows } = await sql.query(text, [community_id]);
    rows[0].headimgurl = getImgurl(rows[0].headimgurl);
    rows[0].coverurl = getImgurl(rows[0].coverurl);
    ctx.body = rows[0];
}

export async function create(ctx: IRouterContext | any) {
    const body = ctx.req.body;
    body.headimgurl = ctx.req.file.filename;
    const client = await sql.connect();
    try {
        await client.query('BEGIN');

        const text = `insert into t_community(headimgurl, name, introduce, tags, pay_cycle, pay_amount, owner)
        values($1, $2, $3, $4, $5, $6, $7) returning id`;
        const params = [body.headimgurl, body.name, body.introduce, JSON.stringify(body.tags.split(',')),
        PayCycle[body.pay_cycle], body.pay_amount as number, body.owner];
        const { rows } = await client.query(text, params);

        const text2 = `insert into t_role(community_id, user_id, role)values($1, $2, $3)`;
        const params2 = [rows[0].id, body.owner, Role[Role.owner]];
        await client.query(text2, params2);

        await client.query('COMMIT');
        body.id = rows[0].id;
        body.headimgurl = getImgurl(body.headimgurl);
        body.tags = body.tags.split(',');
        ctx.body = body;
    } catch (error) {
        await client.query('ROLLBACK');
        throw error;
    } finally {
        client.release();
    }

}

export async function updateCoverurl(ctx: IRouterContext | any) {
    const coverurl = ctx.req.file.filename;
    const text = `update t_community set coverurl=$1 where id=$2`;
    const params = [coverurl, ctx.params.id];
    const res = await sql.query(text, params);
    ctx.body = { url: getImgurl(coverurl) };
}

export async function updateHeadimgurl(ctx: IRouterContext | any) {
    const headimgurl = ctx.req.file.filename;
    const text = `update t_community set headimgurl=$1 where id=$2`;
    const params = [headimgurl, ctx.params.id];
    const res = await sql.query(text, params);
    ctx.body = { url: getImgurl(headimgurl) };
}

export async function findByOpenid(ctx: IRouterContext) {
    const openid = ctx.query.openid;
    const text = `SELECT
    c.id,
    c.name,
    c.headimgurl,
    c.coverurl,
    c.introduce,
    c.tags,
    c.pay_cycle,
    c.pay_amount,
    c.owner,
    c.wechat_nickname,
    c.wechat_qrcodeurl,
    c.wechat_oriheadimgurl
  FROM t_community c
    JOIN t_role r ON c.id = r.community_id WHERE r.user_id=$1 and c.deleted_at is null`;
    const { rows } = await sql.query(text, [openid]);
    for (let row of rows) {
        row.headimgurl = getImgurl(row.headimgurl);
        row.coverurl = getImgurl(row.coverurl);
    }
    ctx.body = rows;
}

export const updateWechat = async (ctx: IRouterContext) => {
    const community_id = ctx.params.id;
    const article_url = ctx.request.body.article_url;
    const publicno = await getPublicNoFromArticleUrl(article_url);
    const text = `update t_community set wechat_nickname=$1, wechat_qrcodeurl=$2, wechat_oriheadimgurl=$3 where id=$4`;
    const { nickname, qrcodeurl, oriHeadimgurl } = publicno;
    const params = [nickname, qrcodeurl, oriHeadimgurl, community_id];
    await sql.query(text, params);
    ctx.body = { nickname: nickname, qrcodeurl: qrcodeurl, oriHeadimgurl: oriHeadimgurl };
}

export const addUser = async (ctx: IRouterContext) => {
    const community_id = ctx.params.id;
    const user_id = ctx.request.body.user_id;
    const { rows } = await sql.query(`select count(1) from t_role where community_id=$1 and user_id=$2`, [community_id, user_id]);
    const count = rows[0].count;
    let res: number = 0;
    if (count == 0) {
        const text = 'insert into t_role (community_id, user_id, role)values($1, $2, $3)';
        const { rowCount } = await sql.query(text, [community_id, user_id, 'member']);
        res = rowCount;
    }
    ctx.body = res;
}

export const findByName = async (ctx: IRouterContext) => {
    const name = ctx.query.name;
    const text = 'select * from t_community where name like $1 and deleted_at is null';
    const { rows } = await sql.query(text, [`%${name}%`]);
    for (let row of rows) {
        row.headimgurl = getImgurl(row.headimgurl);
        row.coverurl = getImgurl(row.coverurl);
    }
    ctx.body = rows;
}

export const remove = async (ctx: IRouterContext) => {
    const community_id = ctx.params.id;
    const user_id = ctx.query.user_id;
    if (!user_id)
        return ctx.status = 400;
    const text = `update t_community set deleted_at=current_timestamp where id=$1 and owner=$2`;
    const { rowCount } = await sql.query(text, [community_id, user_id]);
    ctx.body = rowCount;
}

export const deleteUser = async (ctx: IRouterContext) => {
    const community_id = ctx.params.id;
    const user_id = ctx.request.body.user_id;
    const text = `delete from t_role where community_id=$1 and user_id=$2 and role!='owner'`;
    const { rowCount } = await sql.query(text, [community_id, user_id]);
    ctx.body = rowCount;
}

export const update = async (ctx: IRouterContext) => {
    const community_id = ctx.params.id;
    const body = ctx.request.body;
    let text = `update t_community set `;
    let count = 0;
    let params: string[] = [];

    for (let key of Object.keys(body)) {
        if (key === 'pay_cycle') {
            text += `${key}=\$${++count},`;
            params.push(PayCycle[body[key]]);
            continue;
        }
        text += `${key}=\$${++count},`;
        params.push(body[key]);
    }

    text = text.substring(0, text.length - 1);
    text += ` where id=\$${++count}`;
    params.push(community_id);
    const { rowCount } = await sql.query(text, params);
    ctx.body = { result: rowCount };
}
